<template>
  <div class="user-message">
    <h2>个人信息管理</h2>
    
    <el-form 
      :model="userForm" 
      :rules="rules"
      ref="formRef"
      label-width="100px"
      class="user-form"
    >
      <!-- 基本信息 -->
      <el-form-item label="账号">
        <span class="info-text">{{ userForm.userid }}</span>
      </el-form-item>

      <el-form-item label="邮箱" prop="email">
        <el-input v-model="userForm.email" placeholder="请输入邮箱">
          <template #prefix>
            <el-icon><Message /></el-icon>
          </template>
        </el-input>
      </el-form-item>

      <el-form-item label="姓名" prop="name">
        <el-input v-model="userForm.name" placeholder="请输入姓名" />
      </el-form-item>

      <el-form-item label="性别" prop="gender">
        <el-radio-group v-model="userForm.gender">
          <el-radio :label="1">男</el-radio>
          <el-radio :label="0">女</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="年龄" prop="age">
        <el-input-number 
          v-model="userForm.age" 
          :min="1" 
          :max="120"
          controls-position="right"
        />
      </el-form-item>

      <!-- 修改密码部分 -->
      <div class="password-section">
        <h3>修改密码</h3>
        <el-form-item label="原密码" prop="oldPassword">
          <el-input 
            v-model="userForm.oldPassword" 
            type="password" 
            :show-password="true"
            placeholder="请输入原密码"
          />
        </el-form-item>

        <el-form-item label="新密码" prop="newPassword">
          <el-input 
            v-model="userForm.newPassword" 
            type="password" 
            :show-password="true"
            placeholder="请输入新密码"
          />
        </el-form-item>

        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input 
            v-model="userForm.confirmPassword" 
            type="password" 
            :show-password="true"
            placeholder="请再次输入新密码"
          />
        </el-form-item>
      </div>

      <!-- 提交按钮 -->
      <el-form-item>
        <el-button type="primary" @click="handleSubmit">保存修改</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { Message } from '@element-plus/icons-vue'
import { updateUserInfo } from '../../api/user'

const formRef = ref<FormInstance>()

// 表单数据
const userForm = reactive({
  userid: localStorage.getItem('userid') || '',
  name: localStorage.getItem('username') || '',
  gender: Number(localStorage.getItem('sex')) || 1,
  age: Number(localStorage.getItem('age')) || 18,
  email: localStorage.getItem('email') || '',
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 验证邮箱格式
const validateEmail = (rule: any, value: string, callback: any) => {
  if (!value) {
    callback()
    return
  }
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  if (!emailRegex.test(value)) {
    callback(new Error('请输入正确的邮箱格式'))
  } else {
    callback()
  }
}

// 表单验证规则
const rules = reactive<FormRules>({
  email: [
    { validator: validateEmail, trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  age: [
    { required: true, message: '请输入年龄', trigger: 'blur' },
    { type: 'number', min: 1, max: 120, message: '年龄必须在1-120岁之间', trigger: 'blur' }
  ],
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== userForm.newPassword) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
})

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 构建更新数据
        const updateData: any = {
          clientId: userForm.userid,
          name: userForm.name,
          sex: userForm.gender,
          age: userForm.age,
          email: userForm.email
        }
        
        // 如果修改了密码，添加密码字段
        if (userForm.newPassword) {
          updateData.password = userForm.newPassword
        }
        
        const res = await updateUserInfo(updateData)
        
        if (res.code === '200') {
          // 更新本地存储的用户信息
          localStorage.setItem('username', userForm.name)
          localStorage.setItem('sex', String(userForm.gender))
          localStorage.setItem('age', String(userForm.age))
          localStorage.setItem('email', userForm.email)
          
          ElMessage.success('保存成功')
          
          // 清空密码字段
          userForm.oldPassword = ''
          userForm.newPassword = ''
          userForm.confirmPassword = ''
        } else {
          ElMessage.error(res.msg || '保存失败')
        }
      } catch (error: any) {
        ElMessage.error(error.message || '保存失败')
      }
    }
  })
}

// 重置表单
const resetForm = () => {
  if (!formRef.value) return
  formRef.value.resetFields()
}
</script>

<style scoped>
.user-message {
  padding: 20px;
}

h2 {
  margin: 0 0 30px;
  font-size: 24px;
  color: #2c3e50;
}

.user-form {
  max-width: 600px;
}

.info-text {
  color: #606266;
}

.password-section {
  margin-top: 40px;
  padding-top: 20px;
  border-top: 1px solid #EBEEF5;
}

.password-section h3 {
  margin: 0 0 20px;
  font-size: 18px;
  color: #2c3e50;
}
</style>